package com.hj.dapp.business.dept.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hj.dapp.business.dept.mapper.DeptMapper;
import com.hj.dapp.business.dept.model.Dept;
import com.hj.dapp.business.dept.service.DeptService;
import com.hj.dapp.common.request.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2023/12/30
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public void saveDept(Dept dept, Principal principal) {
        //生成排序字段
        if (ObjectUtils.isEmpty(dept.getOrderNum())) {
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", dept.getParentId());
            Long sort = deptMapper.selectCount(queryWrapper);
            sort++;
            dept.setOrderNum(sort.intValue());
        }
        dept.setCreateTime(LocalDateTime.now());
        dept.setCreateBy(principal.getName());
        deptMapper.insert(dept);
    }

    @Override
    public void editDept(Dept dept, Principal principal) {
        dept.setLastUpdateTime(LocalDateTime.now());
        dept.setLastUpdateBy(principal.getName());
        deptMapper.updateById(dept);
    }

    @Override
    public List<Dept> listDept(Dept dept) {
        return deptMapper.selectList(null);
    }

    @Override
    public IPage<Dept> pageDept(PageRequest<Dept> request) {
        return deptMapper.selectPage(request.getPage(),null);
    }

}
